package com.coalmine.api.tasks;

import com.coalmine.api.domain.ApiStat;
import com.coalmine.api.service.IApiStatService;
import com.coalmine.common.constant.CacheConstants;
import com.coalmine.common.core.redis.RedisCache;
import com.coalmine.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Component
public class ApiStatTask {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IApiStatService apiStatService;

    @Scheduled(cron = "0 0 1 * * ? ")
    public synchronized void syncStat() {
        log.info("Begin to sync api stat info to db...");
        String dayBefore = DateUtils.parseDateToStr(DateUtils.YYYYMMDD, DateUtils.addDays(DateUtils.getNowDate(), -1));
        String keyPattern = CacheConstants.DATE_API_USER_STAT + ":" + dayBefore + ":*";
        Collection<String> beforeList = redisCache.keys(keyPattern);
        log.info("Redis cache list {}", beforeList);
        List<ApiStat> statList = new ArrayList<>();
        beforeList.stream().forEach(b -> {
            statList.add(redisCache.getCacheObject(b));
        });
        apiStatService.saveBatch(statList);
    }
}
